<?php

namespace App\Services;

use App\Models\ES\User AS esUser;
use App\Models\ES\Media AS esMedia;
use App\Models\Friend;
use App\Models\FriendModel;
use App\Models\Media;
use App\Models\User;
use App\Models\UserTicket;

class ElasticService {

    public static function addMedia(){
        $id = (int)IT('id',true);
        
        $media = D('media')->select(["id AS mid",'title',"description","cover"])->where([['id','=',$id]])->first();
        if(!$media){
            return '非法请求';
        }

        $esMedia  = new esMedia();
        $es_user = $esMedia->getByFid('mid',$id);
        if($es_user && $es_user['total']>0){
            return '请勿重复添加数据';
        }
        
        $info = $esMedia->index($media);
        return $info ? $info :"添加数据失败";
    }

    public static function addUser($id=0){
        if(empty($id))
            return ['status'=>'error', 'message_code'=>10140, 'message'=>'未知用户'];

        $users = User::where([['id','=',$id]])->first();
        if(empty($users))
            return ['status'=>'error', 'message_code'=>10140, 'message'=>'未知用户'];

        $esUser  = new esUser();
        $es_user = $esUser->getByFid('uid',$id);
        if($es_user && $es_user['total']>0)
            return ['status'=>'error', 'message_code'=>10141, 'message'=>'请勿重复添加数据'];
        $params = [
            'uid' => $users->id,
            'username'  => $users->name,
            'mobile' => $users->mobile
        ];

        $info = $esUser->index($params);
        if(empty($info))
            return ['status'=>'error', 'message_code'=>10142, 'message'=>'添加失败'];

        return ['status'=>'success', 'message_code'=>10143, 'message'=>'添加成功'];
    }

    public static function getMedialist(){

        $page = (int)IT('page',1);
        $size = (int)IT('pagesize',10);
        $keyword = IT('keyword',true);
        $ticket = IT('ticket');
        $ClientSource = IT('ClientSource');
        $from = ($page-1)*(int)$size;

        $esUser  = new esMedia();
        $list = $esUser->get_list($keyword,$size,$from);

        $total_page = intval(ceil($list['total']/$size));
        $result['next_page'] = ($total_page<=0 || $page>= $total_page) ? 0 : 1;
        $result['list'] = null;

        if(!empty($list['hits'])){

            $friend_arr = [];
            // 获取用户新
            $user_info = UserTicket::select(['uid'])->where([['ticket', '=', $ticket], ['client_source', '=', $ClientSource], ['status', '=', 1]])->first();
            if(!empty($user_info)){
                // 获取亲友
                $friend_user_list = FriendModel::getListArr([['uid', '=', $user_info->uid]]);
                foreach ($friend_user_list as $fkey=>$fvalue)
                    $friend_arr[] = $fvalue->friend_uid;
            }
            $temp_arr = [];
            foreach ($list['hits'] as &$value) {
                $title = (isset($value['highlight']) && isset($value['highlight']['title']) && !empty($value['highlight']['title'])) ? $value['highlight']['title'][0] : $value['_source']['title'];
                $description = (isset($value['highlight']) && isset($value['highlight']['description']) && !empty($value['highlight']['description'])) ? $value['highlight']['description'][0] : (!isset($value['_source']['description']) ? '' : $value['_source']['description']);
                $temp_arr['title'] = "<font style='color: #ffffff;'>".$title."</font>";
                $temp_arr['description'] = "<font style='color: #ffffff;'>".$description."</font>";
                $medias = Media::getRowsArray([['id', '=', $value['_source']['mid']]], ['id', 'uid'], ['users']);
                if(!empty($medias['users']))
                    $temp_arr['avatar'] = empty($medias['users']['avatar']) ? '' : getSignUrl($medias['users']['avatar']);
                $temp_arr['cover'] = empty($value['_source']['cover']) ? '' : getSignUrl($value['_source']['cover']);
                $temp_arr['media_id'] = $value['_source']['mid'];
                $temp_arr['uid'] = $value['_source']['uid'];
                $temp_arr['is_private'] = $value['_source']['is_private'];

                $tips = null;
                if($value['_source']['is_private'] == 2){
                    if(empty($user_info))
                        $tips = 10145;// trans('notice.10145');//'未登录不能查看亲友圈视频';

                    if(empty($tips) && $user_info->uid != $value['_source']['uid'] && !in_array($value['_source']['uid'], $friend_arr))
                        $tips = 10146;//trans('notice.10146');//'您还不是亲友，不能查看该视频！';
                }
                $temp_arr['tips'] = $tips;

                $result['list'][] = $temp_arr;
            }
        }
        return $result;
    }

    public static function getUserlist(){

        $page = (int)IT('page',1);
        $size = (int)IT('pagesize',10);
        $keyword = IT('keyword',true);
        $ticket = IT('ticket');
        $client_source = IT('ClientSource',true);
        $from = ($page-1)*(int)$size;

        $esUser  = new esUser();
        $list = $esUser->get_list($keyword,$size,$from);

        $result = [];
        $total_page = intval(ceil($list['total']/$size));
        $result['next_page'] = ($total_page<=0 || $page>= $total_page) ? 0 : 1;
        $result['list'] = null;

        if(isset($list['hits']) && !empty($list['hits'])){
            $uid = D('user_tickets')->where([['ticket', '=', $ticket],['client_source',"=",$client_source], ['status', '=', 1]])->value('uid');
            $temp_arr = [];
            foreach ($list['hits'] as &$value) {

                $users = User::select('avatar')->where([['id', '=', $value['_source']['uid']]])->first();
                $is_friend = 0;
                $is_attention = 0;
                if(!empty($uid)){
                    $where = [['uid','=',$uid],['friend_uid',"=",$value['_source']['uid']],['status',"=",1]];
                    $fcnt = FriendModel::where($where)->count();
                    $is_friend = $fcnt ? 1 : 0;

                    $where = [['uid','=',$uid],['friend_id',"=",$value['_source']['uid']],['status',"=",1]];
                    $fucnt = Friend::where($where)->count();
                    $is_attention = $fucnt ? 1 : 0;
                }

                $uid_html = (isset($value['highlight']) && isset($value['highlight']['uid']) && !empty($value['highlight']['uid'])) ? $value['highlight']['uid'][0] : $value['_source']['uid'];
                $username_html = (isset($value['highlight']) && isset($value['highlight']['name']) && !empty($value['highlight']['name'])) ? $value['highlight']['name'][0] : $value['_source']['name'];

                $temp_arr['uid'] = $value['_source']['uid'];
                $temp_arr['uid_html'] = "<font style='color: #ffffff;'>".$uid_html."</font>";
                $temp_arr['username'] = "<font style='color: #ffffff;'>".$username_html."</font>";

                $temp_arr['is_friend'] = $is_friend;
                $temp_arr['is_attention'] = $is_attention;
                $temp_arr['avatar'] = (empty($users) || empty($users->avatar)) ? '' : getSignUrl($users->avatar) ;
                $result['list'][] = $temp_arr;
            }
        }
        return $result;
    }

    /**
     * 将字符串分割为数组    
     * @param  string $str 字符串
     * @return array       分割得到的数组
     */
    public static function mb_str_split($str){
        return preg_split('/(?<!^)(?!$)/u',$str);
    }

    public static function _mbStrSplit ($string, $len=1) {
        $start = 0;
        $strlen = mb_strlen($string);
        while ($strlen) {
            $array[] = mb_substr($string,$start,$len,"utf8");
            $string = mb_substr($string, $len, $strlen,"utf8");
            $strlen = mb_strlen($string);
        }
        return $array;
    }

}
